#
# YEST! system
#

import md5
import os
import tempfile
import sys
import string
import traceback

def createBSScript(bootcheck, bootmapdir):
    res = []
    for hdd in bootcheck:
        bsname = os.path.join(bootmapdir, string.replace(hdd, '/', '_'))
        res.append('dd if=%s of=%s bs=512 count=1' % (hdd, bsname))
    return res

def performActions(config, shFileName, supportFileName, fsmapdir, bootmapdir, tempDir):
    sh = open(shFileName, 'w')

# reading config
    res = {}
    execfile(config, {}, res)
    fscheck = res['fscheck']
    bootcheck = res['bootcheck']
    mountlist = res['mountlist']

# checking symlinks
    for d in (fsmapdir, bootmapdir):
        if os.path.exists(d):
            raise RuntimeError('Utility directory already exists: %s' % d)

# creating support/symlinks
    os.system('rm -Rv %s' % tempDir)
    os.system('mkdir %s' % tempDir)
    os.system('mkdir %s' % os.path.join(tempDir, 'bs'))
    
    os.system('ln -s / %s' % fsmapdir)
    os.system('ln -s %s %s' % (os.path.abspath(os.path.join(tempDir, 'bs')), bootmapdir))

    sh.write('mkdir %s\n' % fsmapdir)
    sh.write('mkdir %s\n' % bootmapdir)

# processing mounts
    for m in mountlist:
	mtab = open('/etc/mtab').read()
        for l in string.split(mtab, '\n'):
            dev, mpoint = string.split(l)[:2]
            if mpoint == m:
                sh.write('umount %s\n' % dev)
                sh.write('mount %s %s%s\n' % (dev, fsmapdir, mpoint))
                break
        else:
            raise RuntimeError('Not all mountpoints mounted: %s' % m)

# creating BS files
    for l in createBSScript(bootcheck, bootmapdir):
        os.system(l)
        sh.write('%s\n' % l)

# processing checksums
    os.system('rm %s' % supportFileName)
    maplist = []
    for d in fscheck:
        maplist.append(fsmapdir + d)
    maplist = maplist + ['%s/*' % bootmapdir]
    for d in maplist:
        os.system("md5sum %s >> %s" % (d, supportFileName))
    sh.write('md5sum -c %s | grep FAILED\n' % os.path.join('/etc/', supportFileName))
    sh.close()

def cleanup(fsmapdir, bootmapdir, tempDir):
# deleting symlinks
    for d in (fsmapdir, bootmapdir):
        if os.path.exists(d):
            os.system('rm %s' % d)
    if os.path.exists(tempDir):
        os.system('rm -Rv %s' % tempDir)

def run(config, shFileName, supportFileName, fsmapdir = '/MSVSgenres_fsmap', bootmapdir = '/MSVSgenres_bsmap', tempDir = 'support'):
    try:
        performActions(config, shFileName, supportFileName, fsmapdir, bootmapdir, tempDir)
    except Exception, e:
        traceback.print_exc()
    cleanup(fsmapdir, bootmapdir, tempDir)

if len(sys.argv) != 4:
    print "Error: Wrong amount of params"
    print "Usage: yest [config-name] [checker-file] [support-file]"
    sys.exit(0)

run(sys.argv[1], sys.argv[2], sys.argv[3])

